package com.android.common.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.net.Network;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.android.common.constant.Constant;
import com.android.common.mvp.model.CodeMsgBean;
import com.android.common.mvp.view.ExceptionView;
import com.android.common.network.CustomNetworkCallback;
import com.android.common.network.NetWorkConnectInfo;
import com.android.common.network.NetworkConnectListener;
import com.android.common.utils.permission.FragmentPermissionDispatcher;
import com.android.common.utils.permission.PermissionCallback;
import com.android.common.widget.AllDialog;
import com.android.common.widget.DialogFactory;

import org.greenrobot.eventbus.EventBus;

/**
 * DialogFragment基类
 */
public abstract class BaseDialogFragment extends DialogFragment
        implements BaseView, PermissionCallback, NetworkConnectListener {
    protected Activity mActivity;
    public Bundle mBundle;
    protected View mRootView;
    protected ExceptionView mErrorView;
    protected AllDialog mLoadingDialog;
    protected AllDialog mPermissionDialog;
    private FragmentPermissionDispatcher dispatcher;
    protected LayoutInflater mLayoutInflater;

    public BaseDialogFragment() {
        // 空构造函数 required for DialogFragment
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = getActivity();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBundle = getArguments();
        if (mBundle == null) {
            mBundle = new Bundle();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mLayoutInflater = inflater;
        mRootView = inflater.inflate(onSetRootViewId(), container, false);
        initErrorView();
        return mRootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (onNeedEventBus()) {
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
        }
        onFindView();
        onInitView();
        onInitEvent();
        onLoadData();
        if (onNeedRequestPermission()) {
            initPermission();
        }
        if (onNeedNetworkListener()) {
            registerNetworkListener();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() != null && getDialog().getWindow() != null) {
            getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (onNeedNetworkListener()) {
            unRegisterNetworkListener();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hideProgress();
        mLoadingDialog = null;
        mPermissionDialog = null;
        if (dispatcher != null) {
            dispatcher.clear(this);
        }
    }

    /**
     * 初始化权限请求器
     */
    private void initPermission() {
        dispatcher = FragmentPermissionDispatcher.getInstance();
        dispatcher.setPermissionCallback(this, this);
        mPermissionDialog = DialogFactory.createPermissionDialog(mActivity);
        dispatcher.checkedWithStorage(this);
    }

    /**
     * 注册网络监听
     */
    @SuppressLint("MissingPermission")
    private void registerNetworkListener() {
        CustomNetworkCallback networkCallback = CustomNetworkCallback.getInstance();
        networkCallback.setListener(this);
        NetWorkConnectInfo.getConnectivityManager().registerDefaultNetworkCallback(networkCallback);
    }

    /**
     * 注销网络监听
     */
    @SuppressLint("MissingPermission")
    private void unRegisterNetworkListener() {
        CustomNetworkCallback networkCallback = CustomNetworkCallback.getInstance();
        NetWorkConnectInfo.getConnectivityManager().unregisterNetworkCallback(networkCallback);
    }

    /**
     * 初始化错误视图
     */
    protected void initErrorView() {
        if (mRootView != null) {
            mErrorView = mRootView.findViewById(com.android.common.R.id.errorView);
            if (mErrorView != null) {
                mErrorView.setOnReloadListener(v -> onErrorClick());
            }
        }
    }

    /**
     * 错误视图点击重试
     */
    protected void onErrorClick() {
        if (mErrorView != null) {
            mErrorView.hide();
        }
        onLoadData();
    }

    /**
     * 显示加载对话框
     */
    public void showProgress() {
        if (isAlive() && !isDetached()) {
            if (mLoadingDialog == null) {
                mLoadingDialog = DialogFactory.createLoading(mActivity);
            }
            mLoadingDialog.show();
        }
    }

    /**
     * 隐藏加载对话框
     */
    public void hideProgress() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    /**
     * 检查Fragment是否存活
     */
    public boolean isAlive() {
        return mActivity != null && !mActivity.isFinishing() && isAdded();
    }

    // =======================================
    // 抽象方法与钩子方法
    // =======================================

    /**
     * 设置布局ID
     */
    protected abstract int onSetRootViewId();

    /**
     * 查找视图
     */
    protected void onFindView() {
    }

    /**
     * 初始化视图
     */
    protected void onInitView() {
    }

    /**
     * 初始化事件
     */
    protected void onInitEvent() {
    }

    /**
     * 加载数据
     */
    protected void onLoadData() {
    }

    /**
     * 是否需要EventBus
     */
    protected boolean onNeedEventBus() {
        return false;
    }

    /**
     * 是否需要请求权限
     */
    protected boolean onNeedRequestPermission() {
        return true;
    }

    /**
     * 是否需要网络监听
     */
    protected boolean onNeedNetworkListener() {
        return false;
    }

    // =======================================
    // 接口实现
    // =======================================

    @Override
    public void onFailed(CodeMsgBean responseBean, String methodName) {
        hideProgress();
        if (isAlive()) {
            Toast.makeText(mActivity, responseBean.getMessage() + "[code=" + responseBean.getCode() + "]", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public <D> void onSucceed(D d, String methodName) {
        hideProgress();
    }

    @Override
    public void onPermission(int request, int state) {
        // 权限回调实现，与BaseFragment保持一致
        switch (request) {
            case Constant.PERMISSION_STORAGE_REQUEST_CODE:
                switch (state) {
                    case PermissionCallback.SUCCESS:
                        dispatcher.checkedWithCamera(this);
                        break;
                    case PermissionCallback.DENIED:
                    case PermissionCallback.NEVER_ASK_AGAIN:
                    case PermissionCallback.EXPLAIN:
                        if (mPermissionDialog != null && !mPermissionDialog.isShowing()) {
                            mPermissionDialog.show();
                        }
                        dispatcher.checkedWithCamera(this);
                        break;
                }
                break;
            // 其他权限处理...
        }
    }

    @Override
    public void onNetworkAvailable(@NonNull Network network) {
        if (isAlive()) {
            Toast.makeText(mActivity, com.android.resource.R.string.network_available, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onNetworkUnavailable() {
        if (isAlive()) {
            Toast.makeText(mActivity, com.android.resource.R.string.network_un_available, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onNetworkLost(@NonNull Network network) {
        if (isAlive()) {
            Toast.makeText(mActivity, com.android.resource.R.string.network_lost, Toast.LENGTH_SHORT).show();
        }
    }
}
